package demo;
//自定义阻塞队列
public class Test12 {
    private String[] data = null;
    private int head = 0;
    private int tail = 0;
    private int size = 0;

    //初始化任务容量
    public Test12(int n){
        data = new String[n];
    }

    //存任务
    public void put(String elem) throws InterruptedException {
        synchronized (this){
            while(size > data.length){
                //阻塞
                this.wait();
            }
            data[tail] = elem;

            if(tail == data.length-1){
                tail = 0;
            }else {
                tail++;
            }
            size++;
            this.notify();
        }
    }
    //取任务
    public String take() throws InterruptedException {
        synchronized (this){
            while (size == 0){
                this.wait();
            }
            String ret = data[head];
            head++;
            if (head >= data.length){
                head = 0;
            }
            size--;
            this.notify();
            return ret;
        }
    }
}
class Main{
    public static void main(String[] args) {
        Test12 queue = new Test12(100);
        Thread producer = new Thread(()->{
            int n = 0;
            while (true){
                n++;
                try {
                    queue.put(n + "");
                    System.out.println("生产了" + n);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        Thread consumer = new Thread(()->{
           while (true){
               try {
                   String n = queue.take();
                   System.out.println("消费了"+n);
               } catch (InterruptedException e) {
                   throw new RuntimeException(e);
               }
           }
        });
        producer.start();
        consumer.start();
    }
}

